<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/8/3
 * Time: 下午5:20
 */

namespace app\wechat\handler;


use app\model\Member;
use app\model\WeChat;
use app\wechat\logic\Configure;
use app\wechat\logic\Vouchers;
use EasyWeChat\Kernel\Contracts\EventHandlerInterface;
use EasyWeChat\Kernel\Messages\Image;
use extend\Functions;

class EventHandler implements EventHandlerInterface
{
    public static $openid = '';

    /**
     * @param null $payload
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function handle($payload = null)
    {
        self::$openid = $payload['FromUserName'];
        switch (strtolower($payload['Event'])) {
            case 'unsubscribe':
                return self::unsubscribe();
                break;
            case 'subscribe':
                return self::subscribe();
                break;
        }
    }
    /**
     * @purpose 用户取消关注公众号
     */
    public static function unsubscribe () {
        $model = new WeChat();
        $model
            ->isUpdate(false)
            ->save(
                ['subscribe' => 0],
                ['openid' => self::$openid]
            );
        return null;
    }

    /**
     * @purpose 用户关注公众号
     * @return string
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function subscribe () {
        $url    = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.Functions::getAccessToken().'&openid='.self::$openid.'&lang=zh_CN';
        $result = \Requests::get($url);
        $result = json_decode($result->body);
        $member = new Member();
        $wechat = new WeChat();
        $uid    = $wechat
            ->where('openid', self::$openid)
            ->value('uid');
        if (!$uid) {
            return '欢迎关注欢乐户外服务!';
        }
        // 构建用户数据
        $member_data = [];
        $member_data['nickname']        = $result->nickname;
        $member_data['sex']             = $result->sex;
//        $member_data['headimgurl']      = $result->headimgurl;
        // 构建wechat表更新数据
        $wechat_data = [];
        $wechat_data['subscribe']       = $result->subscribe;
        $wechat_data['subscribe_time']  = $result->subscribe_time;
        $wechat_data['subscribe_scene'] = $result->subscribe_scene;
        $wechat_data['unionid']         = $result->unionid;
        $member->save($member_data, ['uid' => $uid]);
        $wechat->save($wechat_data, ['uid' => $uid]);
        return '欢迎关注欢乐户外服务!';
    }
}